import string
import random

from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render, redirect,reverse
from glauth.models import VerificationModel
# 导入装饰器
from django.views.decorators.http import require_http_methods
from .forms import RegisterForm,LoginForm
from django.contrib.auth import get_user_model, login, logout

User = get_user_model()

# Create your views here.
@require_http_methods(['GET','POST'])
def gllogin(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            remember = form.cleaned_data.get('remember',0)
            print(remember)
            user = User.objects.filter(email=email).first()
            if user and user.check_password(password):
                # 登录
                login(request,user)
                if not remember:
                    # 如果没有点击记住我，设置过期时间为0，即关闭浏览器就会过期
                    request.session.set_expiry(0)
                else:
                    # 如果点击了记住我，设置过期时间为两周，即关闭浏览器不会过期
                    request.session.set_expiry(1209600)
                return redirect(reverse('blog:index'))
            else:
                print('邮箱或密码错误')
                # form.add_error('email','邮箱或密码错误')
                # return render(request, 'login.html', {'form': form})
                return redirect(reverse('glauth:login'))
        else:
            print(form.errors)
            return redirect(reverse('glauth:login'))

def gllogout(request):
    logout(request)
    return redirect(reverse('blog:index'))

@require_http_methods(['GET','POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            password = form.cleaned_data.get('password')
            username = form.cleaned_data.get('username')
            User.objects.create_user(username=username, email=email, password=password)
            return redirect(reverse('glauth:login'))
        else:
            print(form.errors)
            return redirect(reverse('glauth:register'))
            #return render(request, 'register.html', {'form': form})
def send_email_verification(request):
    #?email=xxxx
    email = request.GET.get('email')
    if not email:
        return JsonResponse({'error': '必须传递邮箱'}, status=400)
    verification = "".join(random.sample(string.digits, k=4))
    #如果有就更新没有创建
    VerificationModel.objects.update_or_create(email=email, defaults={'verification': verification})
    # TODO: 发送验证码到邮箱
    send_mail('验证码', f"验证码{verification}", None, [email])
    return JsonResponse({"message": "验证码已发送成功","code": 200})